package it.polimi.swKnights.SWIMv2.servlets.abilities;

import it.polimi.swKnights.SWIMv2.ejb.abilityManager.AbilityRequestHandlerRemote;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.AlreadyExistingAbilityException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.BadNameAbilityException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidLoginPrivilegesException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.LoginFailException;
import it.polimi.swKnights.SWIMv2.general.Errors;
import it.polimi.swKnights.SWIMv2.general.WebsiteParameters;
import it.polimi.swKnights.SWIMv2.servlets.SwimServlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class AskAbilityProceed
 */
public class AskAbilityProceed extends SwimServlet
{
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		this.seveRequestOfAbility(request, response);
	}

	private void seveRequestOfAbility(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException

	{
		HttpSession session = request.getSession();
		String userName = (String) session.getAttribute("userName");
		String password = (String) session.getAttribute("password");
		String abilityName = getParameterNotNull(request, "name");
		String abilityDescription = getParameterNotNull(request, "description");

		try
		{
			this.handleAbilityCreation(userName, password, abilityName,
					abilityDescription);
			String destination = WebsiteParameters.registeredUserHome;
			response.sendRedirect(destination);
			return;
		}
		catch (AlreadyExistingAbilityException e)
		{

			String destination ="./"+WebsiteParameters.registeredUserHome;
			
			response.sendRedirect(destination+"?error="+Errors.alreadyexistingability);
			

		}
		catch (LoginFailException e)
		{
			response.sendRedirect("./siteHome?error="+Errors.session);
			
		}
		catch (InvalidLoginPrivilegesException e)
		{
			response.sendRedirect("./siteHome?error="+Errors.notuser);
		} 
		catch (BadNameAbilityException e) 
		{
			response.sendRedirect("./siteHome?error="+Errors.tooShortAbilityName);
		}

		

	}

	private String handleAbilityCreation(String userName, String password,
			String name, String description)
			throws AlreadyExistingAbilityException, LoginFailException,
			InvalidLoginPrivilegesException, BadNameAbilityException

	{

		AbilityRequestHandlerRemote abilityBean = this
				.lookUp(AbilityRequestHandlerRemote.class);

		abilityBean.createAbility(userName, password, name, description);

		

		return "";

	}

	private String getParameterNotNull(HttpServletRequest request,
			String parameter)
	{
		String par = request.getParameter(parameter);
		return par == null ? "" : par;
	}

}
